<?php

namespace app\logic\crontab;

use app\model\Shop;
use Swoole\Process;
use think\App;
use think\facade\Config;

class Order
{
    /**
     * 拉取所有平台和客户的订单
     * @param $params array 参数
     * @return void
     */
    public function batchPull($params, App $app) {
        $where = [
            'status' => 1
        ];
        //网店编码
        if (isset($params['code']) && !empty($params['code'])) {
            $where['code'] = trim($params['code']);
        }
        //客户id
        if (isset($params['customer_id']) && !empty($params['customer_id'])) {
            $where['customer_id'] = trim($params['customer_id']);
        }
        //平台id
        if (isset($params['platform_id']) && !empty($params['platform_id'])) {
            $where['platform_id'] = trim($params['platform_id']);
        }
        Shop::where($where)
            ->field('customer_id,platform_id,params,id,last_time')
            ->select()
            ->each(function ($item) use($app) {
                $process = new process($this->pullProcess($item, $app));
                $process->start();
            });
        while ($ret = Process::wait()) {
            echo "订单下载:PID={$ret['pid']}进程结束", PHP_EOL;
        }
    }

    /**
     * 拉取网店订单
     * @param $shop Shop 店铺
     * @return callable
     */
    public function pullProcess(Shop $shop, App $app) : callable {
        return function($process) use($shop, $app) {
            $platform = Config::get('tap.platform');
            if (!isset($platform[$shop->platform_id])) {
                return;
            }
            $app->invokeMethod([$platform[$shop->platform_id]['class'], 'pullOrder'], [$shop]);
        };
    }
}
